package com.zhouheng.springbootpython.common.utils;

import lombok.Cleanup;
import lombok.extern.log4j.Log4j2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 命令工具类
 *
 * @author 周恒
 * @date 20180905 17:58:34
 * @since v1.0
 */
@Log4j2
public class CommandUtil {

    private CommandUtil(){

    }

    /**
     * SUCCESS_CODE 执行成功返回状态
     */
    private static final int SUCCESS_CODE = 0;

    /**
     * GBK，返回数据编码类型
     * GBK包含全部中文字符;
     * UTF-8则包含全世界所有国家需要用到的字符
     */
    private static final String GBK = "GBK";


    /**
     * 通过命令行调用脚本,返回值为0时调用成功
     *
     * @author 周恒
     * @date 20190107 14:30:17
     * @since v1.0
     */
    public static boolean execRuntime(String ... parameters) throws IOException, InterruptedException {
        Process pr = Runtime.getRuntime().exec(parameters);
        pr.getErrorStream().close();
        pr.getOutputStream().close();
        return SUCCESS_CODE == pr.waitFor();
    }

    /**
     * 通过命令行调用脚本，并返回数据
     *
     * @author 周恒
     * @date 20190107 14:13:39
     * @since v1.0
     */
    public static String execRuntimeReturnValue(String ... parameters) throws IOException, InterruptedException{
        Process pr = Runtime.getRuntime().exec(parameters);
        pr.getErrorStream().close();
        pr.getOutputStream().close();
        StringBuilder sb = new StringBuilder();
        //windows环境下已经测试，要用GBK，不然会出现中文乱码
        @Cleanup BufferedReader in =  new BufferedReader(new InputStreamReader(pr.getInputStream(),GBK));
        String line;
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }
        pr.waitFor();
        return sb.toString();
    }

    public static void main(String[] args) throws Exception{
        boolean b = execRuntime("ipconfig");
        System.out.println(b);
        String result = execRuntimeReturnValue("ipconfig","-all");
        System.out.println(result);
    }

}
